const Router = require('koa-router')
const mongoose = require('mongoose')

let router = new Router()

router.post('/regist', async(ctx) => {
    const User = mongoose.model('User')
    let newUser = new User(ctx.request.body)
    await newUser.save().then(() => {
        ctx.body = {
            code: 200,
            message: '注册成功'
        }
    }).catch(err => {
        ctx.body = {
            code: 500,
            message: err
        }
    })
})

router.post('/login', async(ctx) => {
    let loginUser = ctx.request.body
    let username = loginUser.userName
    let password = loginUser.passWord
    
    const User = mongoose.model('User')
    
    await User.findOne({userName: username}).exec().then(async (result) => {
        if(result) {
            let newUser = new User()
            await newUser.comparePassword(password, result.passWord).then((isMatch) => {
                ctx.body = {
                    code: 200,
                    message: isMatch
                }
            }).catch(err => {
                ctx.body = {
                    code: 301,
                    message: '登录失败'
                }
            })
        } else {
            ctx.body = {
                code: 300,
                message: '用户名不存在'
            }
        }
    }).catch(err => {
        ctx.body = {
            code: 500,
            message: '登录失败'
        }
    })

})

module.exports = router